<template>
  <a-button type="primary" ghost :loading="loading" @click="exportExcel()">{{ btnName }}</a-button>
</template>

<script setup>
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import { http } from '@/utils/request'

const props = defineProps({
  searchParams: {
    type: Object,
    default: () => ({})
  },
  type: {
    type: String,
    default: '门诊'
  },
  name: {
    type: String,
    default: '导出'
  },
  code: {
    type: String,
    default: ''
  },
  btnName: {
    type: String,
    default: '导出'
  }
})

const parameters = ref({})
const loading = ref(false)
const exportExcel = () => {
  loading.value = true
  http
    .post('/insure/export', { tblcode: props.code }, { responseType: 'blob', loading: true })
    .then((res) => {
      let fileName = ''
      const dispositionStr = res.headers['content-disposition']
      if (dispositionStr == null || dispositionStr === '') {
        fileName = props.name + 'XLSX'
        return
      }
      const dispositionArr = dispositionStr.split('=')[1]
      fileName = decodeURIComponent(dispositionArr)
      const href = URL.createObjectURL(res.data)
      const element = document.createElement('a')
      element.download = fileName
      element.href = href
      element.click()
      loading.value = false
    })
    .catch(() => {
      message.error('导出失败，请稍后重试！')
    })
}
watch(
  () => props.searchParams,
  (val) => {
    const { dateRange, ...rest } = val
    parameters.value = {
      ...rest,
      ...(dateRange && { stdate: dateRange[0], eddate: dateRange[1] })
    }
  },
  { deep: true, immediate: true }
)
</script>
<style lang="less" scoped></style>
